package com.dminvoicemanager.printdoc;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.dminvoicemanager.DM_InvoiceMenu;
import com.dminvoicemanager.DM_List_Expand_Helper;
import com.dminvoicemanager.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class DM_Print_StockLoading extends Activity {
	private static final String TAG = null;
	private String DBNAME = "dminvoicemanager.db";
	SQLiteDatabase mydb;
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";
	private String USER_SETTINGS = "usersettings";
	String currentRefNo, PRINTER_MAC_ID;
	TextView printrefno, printdate, printloadfrom, printloadto, printtotcases,
			printtotpieces, printtotvalue;
	String item_result_1 = "0", item_result_2 = "0", item_result_3 = "0",
			item_result_4 = "0", stLoadDate, loadFrom, LoadTo;
	double totCases = 0.0, totPieces = 0.0, totAmount = 0.0;

	public void BackToMainMenu(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	public void PrintCurrentview(View view) {
		checkPrinter();
		if (PRINTER_MAC_ID.equals("404")) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Print_StockLoading.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("PRINTER CONFIGURATION");
			// Setting Dialog Message
			alertDialog
					.setMessage("Bluetooth Printer Not Configured.Enter Printer Address");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
		} else {
			Intent myIntent = new Intent(view.getContext(),
					DM_Print_StockLoading_Active.class);
			myIntent.putExtra("TAGIDREFNO", currentRefNo);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
		}
	}

	private void checkPrinter() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUserSettings = null;
		try {
			curUserSettings = mydb.query(USER_SETTINGS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}

		if (curUserSettings != null) {
			if (curUserSettings.getCount() > 0) {
				while (curUserSettings.moveToNext()) {
					PRINTER_MAC_ID = curUserSettings.getString(8);
					if(PRINTER_MAC_ID.trim().length()==0){
						PRINTER_MAC_ID ="404";
					}
					else{
						PRINTER_MAC_ID =curUserSettings.getString(8);
					}
				}
			}
		}
	}

	DecimalFormat formatValues = new DecimalFormat("#,###.00");

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_transaction_doc_stloading);
		Bundle bundle = getIntent().getExtras();
		currentRefNo = bundle.getString("TAGIDREFNO");

		printrefno = (TextView) findViewById(R.id.printrefno);
		printdate = (TextView) findViewById(R.id.printdate);
		printloadfrom = (TextView) findViewById(R.id.printloadfrom);
		printloadto = (TextView) findViewById(R.id.printloadto);
		printtotcases = (TextView) findViewById(R.id.printtotcases);
		printtotpieces = (TextView) findViewById(R.id.printtotpieces);
		printtotvalue = (TextView) findViewById(R.id.printtotvalue);
		TextView txtHeading = (TextView) findViewById(R.id.txtHeading);
		txtHeading.setText("Stock Loading");
		TextView printpreviewtitle = (TextView) findViewById(R.id.printpreviewtitle);
		printpreviewtitle.setText("Stock Loading");
		printSummary();
		PrintListStockLoading();
	}

	private void printSummary() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdessum = null;
		try {
			String query = "SELECT * fROM frepStockLoadingSummary WHERE tempRepStLoadRefNo ='"
					+ currentRefNo + "'";
			allrowitemsdessum = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (allrowitemsdessum != null) {
			if (allrowitemsdessum.getCount() > 0) {
				while (allrowitemsdessum.moveToNext()) {
					stLoadDate = allrowitemsdessum.getString(9);
					String fromloc = allrowitemsdessum.getString(10);
					String toloc = allrowitemsdessum.getString(11);
					String[] loadFromAr = fromloc.split("/");
					loadFrom = loadFromAr[0]; // invcuscode
					String[] loadToAr = toloc.split("/");
					LoadTo = loadToAr[1]; // invcusname

				}
			}
		}
		allrowitemsdessum.close();
		mydb.close();
	}

	private void PrintListStockLoading() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dmstockloadingdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "item_result_1", "item_result_2",
				"item_result_3" };

		int[] totrdes = new int[] { R.id.print_item1, R.id.print_item2,
				R.id.print_item3 };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		Cursor allrowitemsdes = null;
		try {
			String query = "SELECT LH.RefNo,LD.CaseQty,LD.PiceQty,LD.Amt,LD.LitemName,LD.RefNo,LD.SeqNo FROM fLoadhed LH,fLoadDet LD WHERE LD.RefNo = LH.RefNo AND  LH.RefNo ='"
					+ currentRefNo + "' AND RecordChecked = '99' order by LD.SeqNo ASC";

			// String query = "SELECT * FROM fLoadDet";
			allrowitemsdes = mydb.rawQuery(query, null);
			if (allrowitemsdes != null) {
				if (allrowitemsdes.getCount() > 0) {
					while (allrowitemsdes.moveToNext()) {
						Log.v(TAG, "POSITIVE");
						// totCases =0.0, totPieces =0.0, totAmount =0.0;
						String StrPrintRefNo = allrowitemsdes.getString(0);
						String StrPrintCaseQty = allrowitemsdes.getString(1);
						Double StrPrintCaseQtyVal = Double
								.parseDouble(StrPrintCaseQty);
						totCases = totCases + StrPrintCaseQtyVal;
						String StrPrintPiceQty = allrowitemsdes.getString(2);
						Double StrPrintPiceQtyVal = Double
								.parseDouble(StrPrintPiceQty);
						totPieces = totPieces + StrPrintPiceQtyVal;
						String StrPrintTotalAmt = allrowitemsdes.getString(3);
						Double StrPrintTotalAmtVal = Double
								.parseDouble(StrPrintTotalAmt);
						StrPrintTotalAmtVal = Math.round(StrPrintTotalAmtVal * 100) / 100.0d;
						StrPrintTotalAmt = formatValues.format(StrPrintTotalAmtVal);
						totAmount = totAmount + StrPrintTotalAmtVal;
						String StrPrintLitemName = allrowitemsdes.getString(4);

						String printSpaceName ="                    ";
						StrPrintLitemName = StrPrintLitemName + printSpaceName;
						String PrintStrPrintLitemName = StrPrintLitemName.substring(0,Math.min(24,StrPrintLitemName.length()));

						String itemCasePieces = printSpaceName + StrPrintCaseQty +"/"+StrPrintPiceQty;
						String PrintitemCasePiecesQty = itemCasePieces.substring(Math.max(itemCasePieces.length() - 8, 0));

						StrPrintTotalAmt = printSpaceName + StrPrintTotalAmt;
						String PrintStrPrintTotalAmt = StrPrintTotalAmt.substring(Math.max(StrPrintTotalAmt.length() - 12, 0));
						
						HashMap<String, String> maptrdes = new HashMap<String, String>();
						maptrdes.put("item_result_1", PrintStrPrintLitemName);
						maptrdes.put("item_result_2", PrintitemCasePiecesQty);
						maptrdes.put("item_result_3", PrintStrPrintTotalAmt);

						// fill in the grid_item layout
						fillMapstrdes.add(maptrdes);
						SimpleAdapter adaptertrdes = new SimpleAdapter(this,
								fillMapstrdes,
								R.layout.dm_transaction_doc_stloading_raw,
								fromtrdes, totrdes);
						lvtypedes.setAdapter(adaptertrdes);

					}
				} else {
					Log.v(TAG, "NEGATIVE");
				}
			}
			allrowitemsdes.close();
			mydb.close();
		} catch (Exception e) {
		}
		// printrefno;printdate;printloadfrom;printloadto;printtotcases;printtotpieces;printtotvalue
		int int_totCases = (int) totCases;
		int int_totPieces = (int) totPieces;
		String printtotCases = Integer.toString(int_totCases);
		String printtotPieces = Integer.toString(int_totPieces);
		String totAmountStr = formatValues.format(totAmount);
		// String printtotAmount = Double.toString(totAmount);

		printrefno.setText(currentRefNo);
		printdate.setText(stLoadDate);
		printloadfrom.setText(loadFrom);
		printloadto.setText(LoadTo);
		printtotcases.setText(printtotCases);
		printtotpieces.setText(printtotPieces);
		printtotvalue.setText(totAmountStr);

		DM_List_Expand_Helper.getListViewSize(lvtypedes);
	}
	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
}
